// tts/siliconflow.js
// SiliconFlow TTS Provider for 胡萝卜插件

import { BaseTTSProvider } from './index.js';

export default class SiliconFlowProvider extends BaseTTSProvider {
    constructor() {
        super();
        this.name = 'SiliconFlow';
    }

    async synthesize(text, settings) {
        this.validateSettings(settings);
        
        if (!text?.trim()) {
            throw new Error('文本不能为空');
        }

        // 确保追加 /audio/speech 路径
        const base = settings.endpoint || 'https://api.siliconflow.cn/v1';
        const endpoint = base.endsWith('/audio/speech') ? base : `${base.replace(/\/$/, '')}/audio/speech`;

        const body = {
            model: settings.model || 'FunAudioLLM/CosyVoice2-0.5B',
            voice: settings.voice || 'FunAudioLLM/CosyVoice2-0.5B:alex',
            input: text,
            format: 'mp3',
            speed: settings.speed || 1
        };

        const response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${settings.key}`,
                'Content-Type': 'application/json',
                'Accept': 'audio/mpeg,application/json'
            },
            body: JSON.stringify(body)
        });

        if (!response.ok) {
            let errorText = `HTTP ${response.status}`;
            try {
                errorText = await response.text();
            } catch (e) {}
            throw new Error(errorText);
        }

        const contentType = response.headers.get('content-type') || '';
        
        if (contentType.includes('audio')) {
            return await response.blob();
        }

        // 处理可能的JSON响应（包含base64音频）
        const jsonData = await response.json();
        if (jsonData && jsonData.audio) {
            const base64Audio = jsonData.audio;
            const binaryString = atob(base64Audio);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            return new Blob([bytes], { type: 'audio/mpeg' });
        }

        throw new Error('未返回音频数据');
    }

    async getModels(settings) {
        this.validateSettings(settings);
        
        // 固定的模型列表
        return [
            { id: 'FunAudioLLM/CosyVoice2-0.5B', name: 'FunAudioLLM/CosyVoice2-0.5B' },
            { id: 'fnlp/MOSS-TTSD-v0.5', name: 'fnlp/MOSS-TTSD-v0.5' }
        ];
    }

    async getVoices(settings) {
        this.validateSettings(settings);
        
        const voices = [];
        const model = settings.model || 'FunAudioLLM/CosyVoice2-0.5B';

        // 预设音色
        if (/^FunAudioLLM\/CosyVoice2-0\.5B$/i.test(model)) {
            const cosyVoices = ['alex', 'benjamin', 'charles', 'david', 'anna', 'bella', 'claire', 'diana'];
            cosyVoices.forEach(voice => {
                voices.push({
                    id: `${model}:${voice}`,
                    name: voice,
                    group: '预设音色 (CosyVoice)'
                });
            });
        }

        if (/^fnlp\/MOSS-TTSD-v0\.5$/i.test(model)) {
            const mossVoices = ['alex', 'anna', 'bella', 'benjamin', 'charles', 'claire', 'david', 'diana'];
            mossVoices.forEach(voice => {
                voices.push({
                    id: `${model}:${voice}`,
                    name: voice,
                    group: '预设音色 (MOSS)'
                });
            });
        }

        // 获取自定义音色
        try {
            const response = await fetch('https://api.siliconflow.cn/v1/audio/voice/list', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${settings.key}`,
                    'Content-Type': 'application/json'
                }
            });

            if (response.ok) {
                const data = await response.json();
                const customVoices = data?.result || data?.results || [];
                
                if (Array.isArray(customVoices)) {
                    customVoices.forEach(voice => {
                        const id = voice?.uri || voice?.id || voice?.voice_id;
                        const name = voice?.name || voice?.customName || voice?.custom_name || '自定义音色';
                        
                        if (id) {
                            voices.push({
                                id: id,
                                name: `${name} (自定义)`,
                                group: '自定义音色'
                            });
                        }
                    });
                }
            }
        } catch (error) {
            console.warn('获取自定义音色失败:', error);
            // 不抛出错误，只是警告
        }

        return voices;
    }

    async uploadVoice(data, settings) {
        this.validateSettings(settings);
        
        const { name, text, audio } = data;
        
        if (!name || !/^[a-zA-Z0-9_-]{1,64}$/.test(name)) {
            throw new Error('音色名称仅允许字母数字-_，最长64字符');
        }
        
        if (!text?.trim()) {
            throw new Error('请填写参考文本');
        }
        
        if (!audio) {
            throw new Error('请提供音频数据');
        }

        const response = await fetch('https://api.siliconflow.cn/v1/uploads/audio/voice', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${settings.key}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                model: 'FunAudioLLM/CosyVoice2-0.5B',
                customName: name,
                text: text.trim(),
                audio: audio
            })
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`HTTP ${response.status}: ${errorText}`);
        }

        const result = await response.json();
        return {
            success: true,
            uri: result?.uri || '未知',
            message: `上传成功，URI: ${result?.uri || '未知'}`
        };
    }

    async deleteVoice(voiceId, settings) {
        this.validateSettings(settings);
        
        if (!voiceId) {
            throw new Error('请选择要删除的音色');
        }

        // 只允许删除自定义音色（通常不含冒号的模型前缀）
        if (voiceId.includes(':')) {
            throw new Error('只能删除自定义音色');
        }

        const response = await fetch('https://api.siliconflow.cn/v1/audio/voice/deletions', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${settings.key}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                uri: voiceId
            })
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`HTTP ${response.status}: ${errorText}`);
        }

        return true;
    }

    validateSettings(settings) {
        super.validateSettings(settings);
        
        if (!settings.voice) {
            throw new Error('请选择音色');
        }
    }
}